package org.opens.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 功能描述
 *
 * @author: zhangyuming
 * @date: 2023/7/20 17:45
 */
@Slf4j
@Component
public class ThreadPoolConfig implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.execute(() -> {
            int i = 1;
            while (true) {
                try {
                    Thread.sleep(500);
                    log.info("线程计数: {}", i++);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        log.info("线程池已经初始化");
        Thread.sleep(5000);
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.execute(() -> {
            int i = 1;
            while (true) {
                try {
                    Thread.sleep(500);
                    System.out.println("线程计数: " + (i++));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        //子线程不停gc，模拟偶发的gc
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    System.gc();
                }
            }
        }).start();
    }

}
